package com.pansoft.openplanet.activity;

import android.annotation.SuppressLint;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.graphics.drawable.BitmapDrawable;
import android.os.Bundle;
import androidx.localbroadcastmanager.content.LocalBroadcastManager;
import android.text.Editable;
import android.text.TextWatcher;
import android.view.Gravity;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.RelativeLayout;
import android.widget.TextView;

import com.efounder.chat.utils.LXGlideImageLoader;
import com.efounder.constant.EnvironmentVariable;
import com.efounder.ospopenplanet.wxapi.WXPayEntryActivity;
import com.efounder.util.ToastUtil;
import com.efounder.utils.ResStringUtil;
import com.pansoft.mobilemallpay.pays.AliPay;
import com.pansoft.mobilemallpay.pays.OnPayListener;
import com.pansoft.mobilemallpay.pays.PayInter;
import com.pansoft.mobilemallpay.pays.WxPay;
import com.pansoft.openplanet.R;
import com.efounder.mvp.base.BasePresenter;
import com.efounder.mvp.base.MvpBaseActivity;
import com.pansoft.openplanet.util.TCMathUtil;
import com.pansoft.openplanet.util.TCRequestUtil;
import com.pansoft.openplanet.util.TcRechargeEncryptUtl;
import com.pansoft.openplanet.widget.RechargeMethodPop;
import com.utilcode.util.ToastUtils;

import org.json.JSONException;
import org.json.JSONObject;

import java.util.HashMap;

/**
 * Created by cimu on 2018/9/17.
 * 积分卡充值界面
 */
public class AmountRechargeActivity extends MvpBaseActivity implements View.OnClickListener {
    public static final String ALI_PAY_TYPE = "ali";
    public static final String WX_PAY_TYPE = "wx";
    private TextView tvCardType, tvCardName, tvAmountRechargeNum, tvAmountRechargeRate;
    private ImageView ivCardPhotoPay;
    private EditText etRechargeAmount;
    private int digits = 2;
    private Button btnNext;
    private View nextView;
    private RelativeLayout rlRechargeMethod;
    /**
     * 充值方式
     */
    private String type;
    /**
     * 兑换比率
     */
    private double conversionRate = 0;
    /**
     * 卡片id
     */
    private String coinId = "4";

    private String title;

    public static void start(Context context, String title, String cardId) {
        Intent starter = new Intent(context, AmountRechargeActivity.class);
        starter.putExtra("title", title);
        starter.putExtra("cardId", cardId);
        context.startActivity(starter);
    }

    @Override
    protected BasePresenter initPresenter() {
        return null;
    }

    @Override
    protected int getContentLayoutId() {
        return R.layout.activity_amount_recharge;
    }

    @Override
    protected void initView(Bundle savedInstanceState) {
        title = getIntent().getStringExtra("title");
        coinId = getIntent().getStringExtra("cardId");
        initView();
    }

    @Override
    protected void initData() {
        showProgress(ResStringUtil.getString(R.string.common_text_loading));
        HashMap<String, String> map = new HashMap<>();
        map.put("cardId", coinId);
        TcRechargeEncryptUtl.setEnceptParam(map);
        TCRequestUtil.getCommonRequest(TAG, TCRequestUtil.RATE_BY_CARDID, map, new TCRequestUtil.TCRequestCallback() {
            @SuppressLint("StringFormatMatches")
            @Override
            public void onSuccess(String response) {
                dismissProgress();
                try {
                    JSONObject jsonObject = new JSONObject(response);
                    String result = jsonObject.optString("result");
                    if (result.equals("success")) {
                        conversionRate = Double.valueOf(jsonObject.optString("data"));
                        tvAmountRechargeRate.setText(String.format(getString(R.string.open_planet_stack_recharge_rate),title,conversionRate+""));
                    }
                } catch (JSONException e) {
                    e.printStackTrace();
                }
            }

            @Override
            public void onFail(String error) {
                dismissProgress();
            }
        });
    }

    @Override
    public void initEvent() {

    }


    public void initView() {
        TextView tvTitle = (TextView) findViewById(R.id.tv_title);
        tvTitle.setText(title+" "+ResStringUtil.getString(R.string.open_planet_charge));
        tvCardType = (TextView) findViewById(R.id.tv_card_type);
        tvCardName = (TextView) findViewById(R.id.tv_card_name);
        ivCardPhotoPay = (ImageView) findViewById(R.id.iv_card_photo_pay);
        etRechargeAmount = (EditText) findViewById(R.id.et_recharge_amount);
        tvAmountRechargeNum = (TextView) findViewById(R.id.tv_amount_recharge_num);
        tvAmountRechargeRate = (TextView) findViewById(R.id.tv_amount_recharge_rate);
        nextView = (View) findViewById(R.id.next_view);
        btnNext = (Button) findViewById(R.id.btn_next);
        btnNext.setOnClickListener(this);
        rlRechargeMethod = (RelativeLayout) findViewById(R.id.rl_recharge_method);
        rlRechargeMethod.setOnClickListener(this);
        etRechargeAmount.addTextChangedListener(textWatcher);
        type = ALI_PAY_TYPE;

    }

    TextWatcher textWatcher = new TextWatcher() {
        @Override
        public void beforeTextChanged(CharSequence charSequence, int i, int i1, int i2) {

        }

        @Override
        public void onTextChanged(CharSequence charSequence, int i, int i1, int i2) {
            if (charSequence.toString().equals("") || charSequence.toString().equals(".")) {
                tvAmountRechargeNum.setText("0");
            } else {
                tvAmountRechargeNum.setText(TCMathUtil.retainAsignDecimalsWithZero( Double.valueOf(charSequence.toString()) * conversionRate,2));
            }
            if (charSequence.toString().contains(".")) {
                if (charSequence.length() - 1 - charSequence.toString().indexOf(".") > digits) {
                    charSequence = charSequence.toString().subSequence(0,
                            charSequence.toString().indexOf(".") + digits + 1);
                    etRechargeAmount.setText(charSequence);
                    tvAmountRechargeNum.setText((TCMathUtil.retainAsignDecimalsWithZero( Double.valueOf(charSequence.toString()) * conversionRate,2)));
                    etRechargeAmount.setSelection(charSequence.length()); //光标移到最后
                }
            }
            //如果"."在起始位置,则起始位置自动补0
            if (charSequence.toString().trim().substring(0).equals(".")) {
                charSequence = "0" + charSequence;
                etRechargeAmount.setText(charSequence);
                tvAmountRechargeNum.setText(TCMathUtil.retainAsignDecimalsWithZero( Double.valueOf(charSequence.toString()) * conversionRate,2));
                etRechargeAmount.setSelection(2);
            }

            //如果起始位置为0,且第二位跟的不是".",则无法后续输入
            if (charSequence.toString().startsWith("0")
                    && charSequence.toString().trim().length() > 1) {
                if (!charSequence.toString().substring(1, 2).equals(".")) {
                    etRechargeAmount.setText(charSequence.subSequence(0, 1));
                    tvAmountRechargeNum.setText(TCMathUtil.retainAsignDecimalsWithZero( Double.valueOf(charSequence.subSequence(0, 1).toString()) * conversionRate,2));
                    etRechargeAmount.setSelection(1);
                    return;
                }
            }

        }

        @Override
        public void afterTextChanged(Editable editable) {
            if (editable.toString().equals("")) {
                btnNext.setClickable(false);
                nextView.setVisibility(View.VISIBLE);
            } else {
                nextView.setVisibility(View.GONE);
                btnNext.setClickable(true);
            }

        }
    };

    @Override
    public void onClick(View view) {
        int id = view.getId();
        if (id == R.id.btn_next) {
            String amount = etRechargeAmount.getText().toString().trim();
            if (amount.equals("")) {
                ToastUtils.showShort(ResStringUtil.getString(R.string.open_planet_asset_amount_recharge_enter_recharge_amount));
                return;
            }
            if (conversionRate == 0) {
                etRechargeAmount.setText("");
                ToastUtils.showShort(ResStringUtil.getString(R.string.common_text_http_request_data_fail));
                initData();
                return;
            }
            requestPlaceOnOrder(type, tvAmountRechargeNum.getText().toString().trim(), coinId, etRechargeAmount.getText().toString().trim());
        } else if (id == R.id.rl_recharge_method) {
            RechargeMethodPop rechargeMethodPop = new RechargeMethodPop(this);
            rechargeMethodPop.setBackgroundDrawable(new BitmapDrawable());
            rechargeMethodPop.setFocusable(true);
            rechargeMethodPop.setOutsideTouchable(true);
            rechargeMethodPop.showAtLocation(this.findViewById(R.id.rl_recharge_method), Gravity.BOTTOM | Gravity.CENTER_HORIZONTAL, 0, 0);
            rechargeMethodPop.setRechargePhoto(new RechargeMethodPop.RechargePhoto() {
                @Override
                public void getRechargePhoto(int position) {
                    if (position == 0) {
                        LXGlideImageLoader.getInstance().displayImage(AmountRechargeActivity.this, ivCardPhotoPay, R.drawable.open_planet_recharge_pay_for);
                        tvCardName.setText(ResStringUtil.getString(R.string.open_planet_pay_for));
                        type = ALI_PAY_TYPE;
                    } else if (position == 1) {
                        LXGlideImageLoader.getInstance().displayImage(AmountRechargeActivity.this, ivCardPhotoPay, R.drawable.open_planet_recharge_we_chat);
                        tvCardName.setText(ResStringUtil.getString(R.string.open_planet_we_chat));
                        type = WX_PAY_TYPE;
                    }
                }

            });
        }
    }


    /**
     * 请求下单
     * > iphone 手机号
     * > payType 支付类型
     * > coinNumber 金额
     * > coinId 积分卡id
     */
    private void requestPlaceOnOrder(String type, String coinNumber, String coinId, String orderAmount) {
        pay(AmountRechargeActivity.this, type, coinNumber, coinId, orderAmount);
    }

    /**
     * 支付订单
     *
     * @param context
     * @param type        支付类型  查看
     * @param orderAmount 订单金额
     */
    public void pay(Context context, String type, String coinNumber, String coinId, String orderAmount) {
        if (coinId == null) {
            ToastUtils.showShort(ResStringUtil.getString(R.string.open_planet_asset_amount_recharge_order_empty));
            return;
        }
        HashMap<String, String> orderBeanMap = new HashMap<>();
        //请求订单号
        PayInter pay = null;
        if (WX_PAY_TYPE.equals(type)) {
            //wx支付
            pay = new WxPay(context);
        } else if (ALI_PAY_TYPE.equals(type)) {
            pay = new AliPay(context);
        }
        orderBeanMap.put("payType", type);
        orderBeanMap.put("iphone", EnvironmentVariable.getUserName());
        if(coinId.equals("5")||coinId.equals("6")||coinId.equals("7")){
            //pdt加address
            orderBeanMap.put("address", EnvironmentVariable.getProperty("tc_ethAddress", ""));
        }

        orderBeanMap.put("coinNumber", coinNumber);
        orderBeanMap.put("coinId", coinId);
        TcRechargeEncryptUtl.setEnceptParam(orderBeanMap);
        //监听页面
        listenerActivityNotifycation();

        pay.setURLAndParams(TCRequestUtil.START_PAY_URL, orderBeanMap);

        //无法直接向wxpayentryactivity传值,如果支付方式是微信的话
        EnvironmentVariable.setProperty("mobile_pay_good_name", ResStringUtil.getString(R.string.app_name));
        EnvironmentVariable.setProperty("mobile_pay_good_description", title+" "+ResStringUtil.getString(R.string.open_planet_charge));
        EnvironmentVariable.setProperty("mobile_pay_good_price", ResStringUtil.getString(R.string.open_planet_asset_amount_recharge_unit) + orderAmount);
        final PayInter finalPay = pay;
        pay.pay(new OnPayListener() {
            @Override
            public void onPaySuccess() {
                ToastUtil.showToast(AmountRechargeActivity.this, ResStringUtil.getString(R.string.open_planet_asset_amount_recharge_pay_success));
                if (finalPay instanceof AliPay) {
                    //阿里支付成功后需要手动跳转到支付成功界面
                    //微信会自动跳转到成功界面;
                    Intent intent = new Intent(AmountRechargeActivity.this, WXPayEntryActivity.class);
                    intent.putExtra("type", "ali");
                    intent.putExtra("status", "success");
                    startActivity(intent);
                    finish();
                }
            }

            @Override
            public void onPayFailure(String msg, int code) {
                if (code == OnPayListener.ERROR) {
                    ToastUtil.showToast(AmountRechargeActivity.this, msg);
                    if (finalPay instanceof AliPay) {
                        //阿里支付成功后需要手动跳转到支付成功界面
                        //微信会自动跳转到成功界面;
                        Intent intent = new Intent(AmountRechargeActivity.this, WXPayEntryActivity.class);
                        intent.putExtra("type", "ali");
                        intent.putExtra("status", "failure");
                        startActivity(intent);
                    }
                }
            }
        });
    }

    /**
     * 页面监听  微信支付回调
     */
    private BroadcastReceiver receiver;
    public void listenerActivityNotifycation() {
        LocalBroadcastManager.getInstance(this).registerReceiver(receiver = new BroadcastReceiver() {
            @Override
            public void onReceive(Context context, Intent intent) {
                LocalBroadcastManager.getInstance(AmountRechargeActivity.this).unregisterReceiver(this);
                finish();
            }
        }, new IntentFilter(WXPayEntryActivity.FINISH_ORDER_ACTIVITY));
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        if (receiver != null) {
            LocalBroadcastManager.getInstance(this).unregisterReceiver(receiver);
        }

    }
}
